#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'tyh'
__mtime__ = '18-9-17'
# code is far away from bugs with the god animal protecting ~
"""

import re

from flask import render_template, current_app, g, request, jsonify, redirect, abort
from flask_wtf import csrf

from info import constants, db
from info.models import Category, News, User
from info.response_code import RET
from info.utils.common import required_login, general_msg
from info.utils.image_storage import storage
from . import bp_users as app


# 用户首页
@app.route("/", methods=["GET"])
@required_login
def users_index():
	user = g.user

	if not user:
		return redirect("/")

	data = {"user_id": user.id, "error": RET.OK}
	data.update(user.to_dict())

	return render_template("news/user.html", **data)


# 1用户基本信息
@app.route("/base_info", methods=["GET", "POST"])
@required_login
def base_info():
	user = g.user

	if not user:
		return general_msg(RET.USERERR, "请先登陆")

	if request.method == "GET":
		return render_template("news/user_base_info.html")
	else:
		get_param = request.json

		signature = get_param.get("signature", None)
		nick_name = get_param.get("nick_name", None)
		gender = get_param.get("gender", None)

		if not all([signature, nick_name, gender]):
			return general_msg(RET.PARAMERR)

		if gender == "0":
			gender = "MAN"
		elif gender == "1":
			gender = "WOMAN"
		else:
			return general_msg(RET.PARAMERR, "用戶性別錯誤错误")

		user.signature = signature
		user.nick_name = nick_name
		user.gender = gender

		try:
			db.session.add(user)
			db.session.commit()
		except Exception as e:
			db.session.rollback()
			current_app.logger.error(e)
			return general_msg(RET.DBERR)

		data = {"errno": RET.OK, "nick_name": nick_name}
		return jsonify(data)


# 2用户头像信息
@app.route("/pic_info", methods=["GET", "POST"])
@required_login
def pic_info():
	user = g.user

	if not user:
		return general_msg(RET.USERERR, "请先登陆")

	if request.method == "GET":
		return render_template("news/user_pic_info.html")
	else:
		get_param = request.files
		avatar = get_param.get("avatar", None) if get_param else None
		if not avatar:
			return general_msg(RET.PARAMERR)

	try:
		avatar_name = storage(avatar.read())
	except Exception as e:
		current_app.logger.error(e)
		return general_msg(RET.THIRDERR)

	user.avatar_url = avatar_name

	try:
		db.session.add(user)
		db.session.commit()
	except Exception as e:
		db.session.rollback()
		current_app.logger.error(e)
		return general_msg(RET.DBERR)

	data = {"errno": RET.OK, "avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_name}
	return jsonify(data)


# 3用户关注信息
@app.route("/follow", methods=["GET"])
@required_login
def follow():
	user = g.user
	if not user:
		return general_msg(RET.USERERR, "请先登陆")

	page = request.args.get("page",None)

	is_index = False
	if page:
		try:
			page = int(page)
		except Exception as e:
			return general_msg(RET.PARAMERR)
	else:
		is_index = True

	paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
	followed = [user.to_dict() for user in paginate.items]

	if is_index:
		return render_template("news/user_follow.html", followed=followed, total_page=paginate.pages, curr_page=paginate.page)
	else:
		param = {"errno": RET.OK, "total_page": paginate.pages, "followed": followed}
		return jsonify(param)


# 4修改密码
@app.route("/pass_info", methods=["GET", "POST"])
@required_login
def pass_info():
	user = g.user

	if not user:
		return general_msg(RET.USERERR, "请先登陆")

	if request.method == "GET":
		return render_template("news/user_pass_info.html")
	else:
		get_param = request.json
		password = get_param.get("password", None)
		new_password = get_param.get("new_password", None)

		# 3密码是否正确
		if not re.match(r"\w{" + str(constants.USER_PASSWD_LENGTH) + ",}$", new_password):
			return general_msg(RET.PARAMERR, "输入的密码错误")

		print(password,new_password)
		if not all([password, new_password]):
			return general_msg(RET.PARAMERR)

		if user.check_password(password):
			user.password = new_password

			try:
				db.session.add(user)
				db.session.commit()
			except Exception as e:
				db.session.rollback()
				current_app.logger.error(e)
				return general_msg(RET.DBERR)
		else:
			return general_msg(RET.PWDERR)

		return general_msg(RET.OK)


# 5用户收藏信息
@app.route("/collection", methods=["GET"])
@required_login
def collection():
	user = g.user
	if not user:
		return general_msg(RET.USERERR, "请先登陆")

	page = request.args.get("page",None)

	is_index = False
	if page:
		try:
			page = int(page)
		except Exception as e:
			return general_msg(RET.PARAMERR)
	else:
		is_index = True

	paginate = user.collection_news.filter(News.status==1).paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
	collections = [news.to_review_dict() for news in paginate.items]

	if is_index:
		return render_template("news/user_collection.html", collections=collections, total_page=paginate.pages, curr_page=paginate.page)
	else:
		param = {"errno": RET.OK, "total_page": paginate.pages, "collections": collections}
		return jsonify(param)


# 6新闻发布
@app.route("/news_release", methods=["GET", "POST"])
@required_login
def news_release():
	user = g.user

	if not user:
		return general_msg(RET.USERERR, "请先登陆")

	if request.method == "GET":
		categorys = Category.query.filter(Category.id>1).all()
		categorys = [category.to_dict() for category in categorys]
		# csrf_token = csrf.generate_csrf()
		return render_template("news/user_news_release.html", categorys=categorys)
	else:
		get_param = request.form
		title = get_param.get("title", None)
		category_id = get_param.get("category_id", None)
		digest = get_param.get("digest", None)
		# index_image_url
		file_image = request.files.get("indeximage", None)
		content = get_param.get("content", None)

		# print(request.files)
		# print(request.form)
		# print(request.json)
		# print(request.data)
		# print(title, digest, category_id, content, file_image, sep="\n")
		if not all([title, digest, category_id, content]):
			return general_msg(RET.PARAMERR)

		if file_image:
			try:
				index_image_url = storage(file_image.read())
			except Exception as e:
				current_app.logger.error(e)
				return general_msg(RET.THIRDERR)
		else:
			index_image_url =None

		news = News()
		news.title = title
		news.source = "个人"
		news.digest = digest
		news.content = content
		news.index_image_url = constants.QINIU_DOMIN_PREFIX + index_image_url if index_image_url else None
		news.category_id = category_id
		news.user_id = user.id


		try:
			db.session.add(news)
			db.session.commit()
		except Exception as e:
			db.session.rollback()
			current_app.logger.error(e)
			return general_msg(RET.DBERR)

		return general_msg(RET.OK)


# 7新闻列表
@app.route("/news_list", methods=["GET"])
@required_login
def news_list():
	user = g.user
	if not user:
		return general_msg(RET.USERERR, "请先登陆")

	page = request.args.get("page",None)

	is_index = False
	if page:
		try:
			page = int(page)
		except Exception as e:
			return general_msg(RET.PARAMERR)
	else:
		is_index = True

	paginate = user.news_list.order_by(News.create_time.desc()).paginate(page, constants.USER_NEWS_MAX_COUNT, False)
	collections = [news.to_review_dict() for news in paginate.items]

	if is_index:
		return render_template("news/user_news_list.html", collections=collections, total_page=paginate.pages, curr_page=paginate.page)
	else:
		param = {"errno": RET.OK, "total_page": paginate.pages, "collections": collections}
		return jsonify(param)


# 8作者的新聞列表 other
@app.route("/other/<int:author_id>", methods=["GET"])
@required_login
def other(author_id):
	user = g.user
	# if not user:
	# 	return general_msg(RET.USERERR, "请先登陆")

	if not isinstance(author_id,int):
		return general_msg(RET.PARAMERR)
	else:
		author = User.query.get(author_id)
		if not author:
			abort(404)

	page = request.args.get("page",None)

	is_index = False
	if page:
		try:
			page = int(page)
		except Exception as e:
			return general_msg(RET.PARAMERR)
	else:
		is_index = True

	paginate = author.news_list.filter(News.status==1).order_by(News.create_time.desc()).paginate(page, constants.USER_NEWS_MAX_COUNT, False)
	collections = [news.to_review_dict() for news in paginate.items]

	if is_index:
		followers = author.followers
		isfollower = True if user in followers else False

		param = {
			"total_page" : paginate.pages,
			"curr_page" : paginate.page,
			"nick_name" : user.nick_name if user else None,
			"user_id" : user.id if user else None,
			"author" : author.to_dict(),
			"collections": collections,
			"isfollower":isfollower
		}
		return render_template("news/other.html", **param)
	else:
		param = {"errno": RET.OK, "total_page": paginate.pages, "collections": collections}
		return jsonify(param)


if __name__ == '__main__':
	pass
